package com.hyc.myvideo.ui.activity.my.fragment.statistics;

import android.widget.GridView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.adapter.my.statistics.StatisticsMemberAdapter;
import com.hyc.myvideo.data.api.model.BaseResult;
import com.hyc.myvideo.data.api.model.UserInfo;
import com.hyc.myvideo.ui.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 我的会员
 * @author gyb
 * @version 1.0
 * @created 2017/07/26
 */
public class StatisticsMemberFragment extends BaseFragment{
    @BindView(R.id.common_gridview_id)
    PullToRefreshGridView toRefreshGridView;
    /**页数*/
    private int page = 1;
    /**是否刷新*/
    private boolean isRefresh = true;
    private StatisticsMemberAdapter adapter = null;
    private List<UserInfo> listData = null;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_common_gridview_10;
    }

    @Override
    protected void initView() {
        listData = new ArrayList<>();
        adapter = new StatisticsMemberAdapter(getActivity(), listData);
        toRefreshGridView.setAdapter(adapter);
        /**设置展示个数*/
        toRefreshGridView.getRefreshableView().setNumColumns(4);
        toRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                requestData(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                requestData(false);
            }
        });

    }



    @Override
    protected void initData() {
        requestData(true);
    }

    private void requestData(boolean isRefresh){
        this.isRefresh = isRefresh;
        if(isRefresh){
            page = 1;
        }else{
            page++;
        }
        api.requestStatisticsMember(page);
    }

    @Override protected void onNexts(String r, String method) {
        BaseResult<List<UserInfo>> result = JSONObject.parseObject(r, new TypeReference<BaseResult<List<UserInfo>>>(){});
        if(result.isCode()){
            if(isRefresh){
                listData.clear();
            }
            listData.addAll(result.getResult());
            adapter.updateListView(listData);
        }
        clearedListView();
    }

    @Override protected void onError() {
        clearedListView();
    }

    /***
     * 关闭刷新
     */
    private void clearedListView(){
        if(toRefreshGridView.isRefreshing()){
            toRefreshGridView.onRefreshComplete();
        }
    }
}
